const { createWalletFromMnemonic, createWalletFromPubkey} = require("../../utils/hermit_util");
const { SecretNetworkClient, MsgSend,MsgExecuteContract } = require('secretjs');
const { getSessionUser, getOrder, createOrder } = require("../../db/index")
const { decryptByPrivateKey } = require("../../utils/encrypt_util")


require('dotenv').config();


exports.queryBalance = async (req, res) => {
    const { sessionid } = req.headers
    if (!sessionid) {
        return res.status(400).send({ error: 'sessionId is required' });
    }
    const { data } = req.body;
   
    if (!data) {
        return res.status(400).send({ error: 'data is required' });
    }

    try {
        const sessionUser = await getSessionUser(sessionid)
        if (!sessionUser || !sessionUser.private_key) {
            return res.status(401).send({ error: 'user unauthorized' });
        }

        const jsonStr = decryptByPrivateKey(sessionUser.private_key, data)
        const obj = JSON.parse(jsonStr)

        const { address,tokenAddress ,decimal} = obj

        if (!address) {
            return res.status(400).send({ error: 'mnemonic is required' });
        }

        const url = process.env.HERMIT_GRPC_WEB_URL;

        const secretjs = await new SecretNetworkClient({
            url,
            chainId: process.env.HERMIT_CHAIN_ID,
            walletAddress: address,
        });
        console.log(tokenAddress);
        if(tokenAddress){
            
        const { exec } = require('child_process');
        const command = "ghmd query hmip20 balance "+tokenAddress+" " +address+" aabbccdd";
        // "ghmd query hmip20 balance  ghm1csfdps345t2chpju29eyk5gj3celnw76y243ly  ghm1msgzy9jp8pycjpahaskc7huvp6ghprlk58whmh aabbccdd";
        
        exec(command, (error, stdout, stderr) => {
            if (error) {
                console.error(`执行命令时发生错误：${error}`);
                res.status(500).send({ error: 'Failed to query balance' });
                return;
            }            
            console.log(`标准输出：\n${stdout}`);
            res.send({ balance: Number(JSON.parse(stdout).balance.amount) /(10**decimal)});
        });
        }else{
        const { balance } = await secretjs.query.bank.balance({
            address: address,
            denom: "ughm",
        });
        res.send({ balance: Number(balance.amount) / 1e6 });
        }

        
    } catch (error) {
        console.error('Error querying balance:', error);
        res.status(500).send({ error: 'Failed to query balance' });
    }
}

exports.transfer = async (req, res) => {
    const { sessionid } = req.headers
    if (!sessionid) {
        return res.status(400).send({ error: 'sessionId is required' });
    }

    const { data } = req.body;
    if (!data) {
        return res.status(400).send({ error: 'data is required' });
    }

    try {
        const sessionUser = await getSessionUser(sessionid)
        if (!sessionUser || !sessionUser.private_key) {
            return res.status(401).send({ error: 'user unauthorized' });
        }

        const jsonStr = decryptByPrivateKey(sessionUser.private_key, data)
        const obj = JSON.parse(jsonStr)
        
        const { wallte, toAddress, amount, orderId , contract} = obj

        if (!wallte || !toAddress || !amount || !orderId) {
            return res.status(400).send({ error: 'wallte, toAddress, and amount are required' });
        }

        const order = await getOrder(orderId)
        if (order) {
            return res.status(403).send({ error: 'duplication of transfer' });
        }

        // const createRes = await createOrder(orderId)
        // if (!createRes) {
        //     return res.status(403).send({ error: 'create order error' });
        // }

        const newWallet =wallte.mnemonic? await createWalletFromMnemonic(wallte.mnemonic):await createWalletFromPubkey(wallte);
        const myAddress = wallte.address;
        const url = process.env.HERMIT_GRPC_WEB_URL;
        const urls = process.env.HERMIT_GRPC_WEB_URLS;
      
        if(contract){
            const { exec } = require('child_process');
            const wallteName= wallte.address+'Hermit'
            const command = "/www/hermit/go-hermit-shell -account="+wallteName+" -amount="+amount+" -contractAddress="+contract+" -reciptient="+toAddress+" -mnemonic='"+wallte.mnemonic+"'";
            // "ghmd query hmip20 balance  ghm1csfdps345t2chpju29eyk5gj3celnw76y243ly  ghm1msgzy9jp8pycjpahaskc7huvp6ghprlk58whmh aabbccdd";
            
            exec(command, (error, stdout, stderr) => {
                if (error) {
                    console.error(`执行命令时发生错误：${error}`);
                    res.status(500).send({ error: 'Failed to query balance' });
                    return;
                }            
                console.log(`标准输出：\n${stdout}`);
                res.send({ data:stdout });
            });

            
            // const codeHash="366f93dc76dc0ecad14780e3adfa1ad238e5727470d4dfddad740250cc977be7"	
            // const msgExecuteContract  = new MsgExecuteContract({
            //     sender: myAddress,
            //     contract_address: contract,
            //     code_hash: codeHash,
            //     msg: {transfer:{recipient:toAddress,amount:String(amount) }},
            //   })
            //   const txResponse = await secretjs.tx.broadcast([msgExecuteContract], {
            //     gasLimit: 20000,
            //     gasPriceInFeeDenom: 0.1,
            //     feeDenom: "ughm",
            // });
    
            // res.send({ transaction: txResponse });
        }else{
            const secretjs = await new SecretNetworkClient({
            url:url,
            chainId: process.env.HERMIT_CHAIN_ID,
            wallet:newWallet,
            walletAddress: myAddress,
        });
        const msg = new MsgSend({
            from_address: myAddress,
            to_address: toAddress,
            amount: [{ denom: "ughm", amount: String(amount) }],
        });

        const txResponse = await secretjs.tx.broadcast([msg], {
            gasLimit: 20000,
            gasPriceInFeeDenom: 0.1,
            feeDenom: "ughm",
        });

        res.send({ transaction: txResponse });
    }
    } catch (error) {
        console.error('Error executing transfer:', error);
        res.status(500).send({ error: 'Failed to execute transfer' });
    }
},


exports.trlist=async (req,res)=>{
    // ghmd query hmip20 transfers ghm1lufnjxpq48eq7rxplv7ezy7ud7u6336z5z75m6 ghm1mc86zyu0qwuv8hj47a9rdvylr5wyfw8yuw0qj2  123
    const { sessionid } = req.headers
    if (!sessionid) {
        return res.status(400).send({ error: 'sessionId is required' });
    }
    const { data } = req.body;
    if (!data) {
        return res.status(400).send({ error: 'data is required' });
    }
    try {
        const sessionUser = await getSessionUser(sessionid)
        if (!sessionUser || !sessionUser.private_key) {
            return res.status(401).send({ error: 'user unauthorized' });        }

        const jsonStr = decryptByPrivateKey(sessionUser.private_key, data)
        const obj = JSON.parse(jsonStr)
        const { address,contract,page } = obj
        if (!address) {
            return res.status(400).send({ error: 'mnemonic is required' });
        }
        const { exec } = require('child_process');
        const command ="ghmd query hmip20 transfers "+contract+" "+address+" abc 0 1000"
        exec(command, (error, stdout, stderr) => {
            if (error) {
                console.error(`执行命令时发生错误：${error}`);
                res.status(500).send({ error: 'Failed to query balance' });
                return;
            }            
            console.log(`标准输出：\n${stdout}`);
            res.send({ data:stdout });
        });

} catch (error) {
    console.error('Error querying balance:', error);
    res.status(500).send({ error: 'Failed to query balance' });
}
}